package br.com.lopes.gci.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public class CpfCnpjConverter implements Converter 
{

    public CpfCnpjConverter() 
    {
    }

    public Object getAsObject(FacesContext context, UIComponent component, String value)
    {       
        return getAsString(context, component, value);
    }

    public String getAsString(FacesContext context, UIComponent component, Object value)
    {
        String cpfCnpj = null;

        if (value instanceof String)
        {
        	cpfCnpj = (String)value;
            
            if (cpfCnpj != null && cpfCnpj.length() > 11){
            	StringBuilder cpfCnpjAsString = new StringBuilder(cpfCnpj);
            	cpfCnpjAsString.insert(2, ".");
            	cpfCnpjAsString.insert(6, ".");
            	cpfCnpjAsString.insert(10, "/");
            	cpfCnpjAsString.insert(15, "-");
                return cpfCnpjAsString.toString();
            } else {
            	StringBuilder cpfCnpjAsString = new StringBuilder(cpfCnpj);
            	cpfCnpjAsString.insert(3, ".");
            	cpfCnpjAsString.insert(7, ".");
            	cpfCnpjAsString.insert(11, "-");
                return cpfCnpjAsString.toString();
            }
            
        }
        return (String)value;
    } 
}

